# Hello World Example
#
# Welcome to the MaixPy IDE!
# 1. Conenct board to computer
# 2. Select board at the top of MaixPy IDE: `tools->Select Board`
# 3. Click the connect buttion below to connect board
# 4. Click on the green run arrow button below to run the script!

import sensor, image, time, lcd
from machine import Timer, UART
from fpioa_manager import fm
lcd.init(freq=15000000)
sensor.reset()                      # Reset and initialize the sensor. It will
                                    # run automatically, call sensor.run(0) to stop
fm.register(7, fm.fpioa.UART1_RX, force = True)             # 配置 9 脚为 UART1_RX 强制注册
fm.register(8, fm.fpioa.UART1_TX, force = True)             # 配置 6 脚为 UART1_TX 强制注册

uart = UART(UART.UART1, 115200, 8, 0, 1)

sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)   # Set frame size to QVGA (320x240)
sensor.set_auto_gain(True) # 自动曝光
sensor.set_auto_whitebal(True) # 自动白平衡
sensor.skip_frames(time = 2000)     # Wait for settings take effect.
sensor.run(1)
clock = time.clock()                # Create a clock object to track the FPS.
dx = 25
dy = 10
area = (dx,dy,160-dx*2,120-dy*2)
while(True):
    clock.tick()                    # Update the FPS clock.
    img = sensor.snapshot()         # Take a picture and return the image.
    blobs = img.find_rects(roi = area,threshold = 20000) #矩形下限 卡一下去掉A4以外大小的矩形
    img.draw_rectangle(area) #板卡着这个矩形放置，内部才会被识别，外部的场馆背景将被忽略
    for b in blobs:
        print(b.corners())
        print(b.magnitude())
        img.draw_circle(b.corners()[0][0], b.corners()[0][1], 5, color = (0, 255, 0))  #控制台调参
        img.draw_circle(b.corners()[1][0], b.corners()[1][1], 5, color = (0, 255, 0))  #控制台调参
        img.draw_circle(b.corners()[2][0], b.corners()[2][1], 5, color = (0, 255, 0))  #控制台调参
        img.draw_circle(b.corners()[3][0], b.corners()[3][1], 5, color = (0, 255, 0))  #控制台调参

        uart.write("A:%d,%d,B:%d,%d,C:%d,%d,E:%d%d,\r\n" % (b.corners()[0][0],b.corners()[0][1],
                                                            b.corners()[1][0],b.corners()[1][1],
                                                            b.corners()[2][0],b.corners()[2][1],
                                                            b.corners()[3][0],b.corners()[3][1],))
    #lcd.display(img)                # Display on LCD
    print(clock.fps())              # Note: MaixPy's Cam runs about half as fast when connected
                                    # to the IDE. The FPS should increase once disconnected.
